package com.springboot.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author peter
 * @title: Test2DatasourceConfig
 * @projectName springAll-peter
 * @description: TODO
 * @date 19-5-5下午5:31
 */


@Configuration
@MapperScan(basePackages = Test2DatasourceConfig.PACKAGE, sqlSessionFactoryRef = "test2SqlSessionFactory")
public class Test2DatasourceConfig {

    //test2dao扫描路径
    static final String PACKAGE = "com.springboot.test2dao";

    // mybatis mapper扫描路径
    static final String MAPPER_LOCATION = "classpath:mapper/test2/*.xml";


    @Bean(name = "test2datasource")
    @ConfigurationProperties("spring.datasource.druid.mysql.test2")
    public DataSource test2DataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "test2TransactionManager")
    public DataSourceTransactionManager test2TransactionManager() {
        return new DataSourceTransactionManager(test2DataSource());
    }


    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2datasource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //如果不使用xml的方式配置mapper，则可以省去下面这行mapper location的配置。
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(Test2DatasourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}
